from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from django.views.decorators.clickjacking import xframe_options_exempt


from .models import *
from .tools import _check_user_, _page_aop_, _save_attr_, _add_edit_del_
from .api import api
from .rabbitmq.helloworld import mq
# from .DbQuery import DbQuery


import json
import redis
import requests

count = 0

def login(request):
    pass


def logout(request):
    pass


# 单表增删改查
@csrf_exempt
# @_check_user_
@_page_aop_
def user(request):
    ctx = {}

    ctx['objects'] = objs = User.objects.all()

    if request.method == 'POST':
        
        action = request.POST.get('action', '')

        _add_edit_del_(User, request, action)

        if action == 'search': # 自定义查询
            pass

        if action == 'validate_name': # 自定义ajax交互
            name = request.POST.get('name', '')
            if User.objects.filter(name=name).exists():
                return JsonResponse({'valid': False})
            else:
                return JsonResponse({'valid': True})


    return (ctx, 'account/user.html')


@api
def testapi(name, password):
    print(name, password)
    return JsonResponse({'success': True})


@api
def testmq(name, password):
    '''rabbitmq 做异步消息队列    要启动consumer   python manage.py rabbitmq_reciever  '''
    global count
    count += 1
    mq().publish(f'name: {name}, password: {password}, count: {count}')
    return JsonResponse({'success': True})


def testredis(request, id):
    from .redis_.redis_ import get_user_info, add_user_info
    info = get_user_info(str(id))
    if not info:
        info = User.objects.filter(id=id).first().json()
        add_user_info(str(id), info)
    print(type(info))
    return JsonResponse({'success': True, 'userinfo': info})


def test(request, id):
    info = User.objects.filter(id=id).first().json()
    return JsonResponse({'success': True, 'userinfo': info})

def test2(request, id):
    return JsonResponse({'success': True })

